package com.sgidi.einvoice.web;

import com.sgidi.einvoice.service.FileConversionService;
import com.sgidi.einvoice.service.PdfBoxKeyWordPosition;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.pdfbox.io.IOUtils;
import org.apache.pdfbox.io.MemoryUsageSetting;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.graphics.image.LosslessFactory;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.util.Matrix;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.Files;
import java.util.List;
import java.util.UUID;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;

import org.apache.pdfbox.pdmodel.PDPageTree;
import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
import org.apache.pdfbox.pdmodel.PDPageContentStream.AppendMode;

import java.awt.geom.AffineTransform;
import java.io.IOException;
import java.io.ByteArrayOutputStream;
import java.util.List;
@RestController
public class PdfController {
    @Value("${user.dir}/data/invoice")
    private String backupPath;

    @PostMapping("/findKeywordcoordinates")
    public ResponseEntity<byte[]> findKeywordCoordinates(
            @RequestParam("file") MultipartFile file,
            @RequestParam("signatureImage") String PartyIdCount,
            @RequestParam("keyword") String keyword)
            throws IOException {
//        String pdfPath = "C:\\Users\\CDD\\Desktop\\测试.pdf";
//        File file1 = new File(pdfPath);
        int rotation= 0;
        PDDocument doc = PDDocument.load(file.getInputStream());


        String path = backupPath+"/测试1.pdf";


        File directory = new File(backupPath);
        if (!directory.exists()) {
            if (!directory.mkdirs()) {
                System.out.println("Failed to create directory: " + backupPath);
            }
        }


        rotation = doc.getPage(0).getRotation();
        for (PDPage page : doc.getPages()) {
            // 重置旋转角度
            page.setRotation(0);
        }
        doc.save(path);
        //doc.save(dest);


        String keyWords = keyword;
        byte[] signatureImageBytes = downloadImage("http://192.168.2.8/sgidi/signpic/lynew/"+PartyIdCount+".png");
        PDImageXObject pdImage = PDImageXObject.createFromByteArray(doc, signatureImageBytes, "signature");
        PdfBoxKeyWordPosition pdf = new PdfBoxKeyWordPosition(keyWords, path);
        PDPageContentStream contentStream = null;
        List<float[]> list = pdf.getCoordinate();

        // 多页pdf的处理
        float imageWidth = 0; // 图像的宽度
        float imageHeight = 0; // 图像的高度
        for (float[] fs : list) {
            PDPage page = doc.getPage((int)fs[2]-1);
            float x = fs[0];
            float y = fs[1];
            System.out.println(pdf.is_isAcross()?"横版":"竖版");
            contentStream = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true);
            // 创建仿射变换以控制图像的缩放、旋转和平移
            //根据rotation便宜签名坐标
            if(pdf.is_isAcross())
            {
                imageWidth = 20;
                imageHeight = 10;
                x=x +25;
                y=y-12;
            }
            else
            {
                imageWidth =10;
                imageHeight =20;
                x=x-12;
                y=y-28;
            }
            AffineTransform at = new AffineTransform(imageWidth*1.3f, 0, 0, imageHeight*1.3f, x, y);
//            AffineTransform at = new AffineTransform();
            //at.scale(10, 50);
//            at.translate(x -21, y);
            if(!pdf.is_isAcross())
                at.rotate(Math.toRadians(270));
            contentStream.drawXObject(pdImage,at);
            contentStream.close();
//            if(!pdf.is_isAcross()){
//                page.setRotation(rotation);
//            }
        }
        // 判断如果 PDF 是竖版，则将其左转 90 度（即旋转 270 度）
        for (PDPage page : doc.getPages()) {
            //if (page.getRotation() == 0 || page.getRotation() == 180) {
                page.setRotation(rotation); // 竖版左转90度（即旋转270度）
            //}
        }

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();


        doc.save(outputStream);
        doc.save(path);
        doc.close();
        //File delete=new File(path);
        //delete.delete();
        byte[] pdfWithSignatureBytes = outputStream.toByteArray();
        return ResponseEntity.ok()
                .contentLength(pdfWithSignatureBytes.length)
                .contentType(org.springframework.http.MediaType.APPLICATION_PDF)
                .body(pdfWithSignatureBytes);
    }
    private byte[] downloadImage(String imageUrl) throws IOException {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            HttpGet httpGet = new HttpGet(imageUrl);
            HttpResponse response = httpClient.execute(httpGet);
            InputStream inputStream = response.getEntity().getContent();
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            return outputStream.toByteArray();
        }
    }

    @PostMapping("/mergeFilesToPdf")
    public ResponseEntity<byte[]> mergeFilesToPdf(
            @RequestParam("files") List<MultipartFile> files)
            throws IOException {

        FileConversionService fileConversionService = new FileConversionService();
        return fileConversionService.handleFileUpload(files);
    }

    @PostMapping("/mergeFilesToWord")
    public ResponseEntity<byte[]> mergeFilesToWord(
            @RequestParam("files") List<MultipartFile> files)
            throws IOException {
        FileConversionService fileConversionService = new FileConversionService();
        return fileConversionService.handleFileUploadByWord(files);
    }
    // 提取页面的内容（文本）
    // 提取页面的内容（文本）
    private static String extractPageContent(PDDocument document, PDPage page) throws IOException {
        PDFTextStripper stripper = new PDFTextStripper();

        // 设置提取的页面范围
        int startPage = document.getPages().indexOf(page) + 1;  // 页码从 1 开始
        int endPage = startPage;

        stripper.setStartPage(startPage);
        stripper.setEndPage(endPage);

        return stripper.getText(document);  // 从整个文档中提取文本
    }
}
